package com.ruoyi.system.service.impl;

import java.util.List;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.AInforMapper;
import com.ruoyi.system.domain.AInfor;
import com.ruoyi.system.service.IAInforService;

/**
 * 分享类别Service业务层处理
 *
 * @author gf
 * @date 2024-10-21
 */
@Service
public class AInforServiceImpl implements IAInforService {
    @Autowired
    private AInforMapper aInforMapper;

    /**
     * 查询分享类别
     *
     * @param id 分享类别主键
     * @return 分享类别
     */
    @Override
    public AInfor selectAInforById(Long id) {
        return aInforMapper.selectAInforById(id);
    }

    /**
     * 查询分享类别列表
     *
     * @param aInfor 分享类别
     * @return 分享类别
     */
    @Override
    public List<AInfor> selectAInforList(AInfor aInfor) {
        return aInforMapper.selectAInforList(aInfor);
    }

    /**
     * 新增分享类别
     *
     * @param aInfor 分享类别
     * @return 结果
     */
    @Override
    public int insertAInfor(AInfor aInfor) {
        aInfor.setCreateTime(DateUtils.getNowDate());
        boolean flag = !aInfor.getParentId().equals(0L);
        AInfor info = aInforMapper.selectAInforById(aInfor.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (flag && info == null && !UserConstants.DEPT_NORMAL.equals(info.getIsShow()))
        {
            throw new ServiceException("分类停用，不允许新增");
        }
        String ancestors = "";
        if(null != info){
            ancestors = info.getAncestors() + ",";
        }
        aInfor.setAncestors(ancestors + aInfor.getParentId());
        return aInforMapper.insertAInfor(aInfor);
    }

    /**
     * 修改分享类别
     *
     * @param aInfor 分享类别
     * @return 结果
     */
    @Override
    public int updateAInfor(AInfor aInfor) {
        aInfor.setUpdateTime(DateUtils.getNowDate());
        AInfor newParentCategory = aInforMapper.selectAInforById(aInfor.getParentId());
        AInfor oldCategory = aInforMapper.selectAInforById(aInfor.getId());
        if (StringUtils.isNotNull(newParentCategory) && StringUtils.isNotNull(oldCategory))
        {
            String newAncestors = newParentCategory.getAncestors() + "," + newParentCategory.getId();
            String oldAncestors = oldCategory.getAncestors();
            aInfor.setAncestors(newAncestors);
            updateAInforChildren(aInfor.getId(), newAncestors, oldAncestors);
        }
        int result = aInforMapper.updateAInfor(aInfor);
        if (UserConstants.DEPT_NORMAL.equals(aInfor.getIsShow()) && StringUtils.isNotEmpty(aInfor.getAncestors())
                && !StringUtils.equals("0", aInfor.getAncestors()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentCategoryStatusNormal(aInfor);
        }
        return result;
    }

    /**
     * 批量删除分享类别
     *
     * @param ids 需要删除的分享类别主键
     * @return 结果
     */
    @Override
    public int deleteAInforByIds(Long[] ids) {
        return aInforMapper.deleteAInforByIds(ids);
    }

    /**
     * 删除分享类别信息
     *
     * @param id 分享类别主键
     * @return 结果
     */
    @Override
    public int deleteAInforById(Long id) {
        return aInforMapper.deleteAInforById(id);
    }

    /**
     * 批量逻辑删除分享类别
     *
     * @param ids 需要删除的分享类别主键
     * @return 结果
     */
    @Override
    public int logicDeleteAInforByIds(Long[] ids) {
        return aInforMapper.logicDeleteAInforByIds(ids);
    }
    /**
     * 逻辑删除分享类别信息
     *
     * @param id 分享类别主键
     * @return 结果
     */
    @Override
    public int logicDeleteAInforById(Long id) {
        return aInforMapper.logicDeleteAInforById(id);
    }

    /**
     * 校验名称是否唯一
     *
     * @param aInfor 分类信息
     * @return 结果
     */
    @Override
    public boolean checkNameUnique(AInfor aInfor) {
        Long id = StringUtils.isNull(aInfor.getId()) ? -1L : aInfor.getId();
        AInfor info = aInforMapper.checkNameUnique(aInfor.getInName(), aInfor.getParentId());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != id.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 根据ID查询所有子分类（正常状态）
     *
     * @param categoryId 分类ID
     * @return 子分类数
     */
    @Override
    public int selectNormalChildrenCategoryById(Long categoryId) {
        return aInforMapper.selectNormalChildrenCategoryById(categoryId);
    }

    /**
     * 修改该分类的父级分类状态
     *
     * @param aInfor 当前分类
     */
    private void updateParentCategoryStatusNormal(AInfor aInfor) {
        String ancestors = aInfor.getAncestors();
        Long[] ids = Convert.toLongArray(ancestors);
        aInforMapper.updateCategoryStatusNormal(ids);
    }

    /**
     * 修改子元素关系
     *
     * @param categoryId 被修改的分类ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateAInforChildren(Long categoryId, String newAncestors, String oldAncestors)
    {
        List<AInfor> children = aInforMapper.selectChildrenById(categoryId);
        for (AInfor child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            aInforMapper.updateCategoryChildren(children);
        }
    }
}
